<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 17-6-15
 * Time: 下午12:55
 */

namespace console\controllers;


use common\components\tools\Tools;
use common\models\Crontab;
use common\models\ImageIndex;
use console\models\app\Order;
use yii\base\ErrorException;
use yii\console\Controller;
use yii\helpers\FileHelper;

class CronController extends Controller
{
    /**
     * php yii cron/delete-old-upload-files
     */
    public function actionDeleteOldUploadFiles()
    {
        $runtime_files_dir = \Yii::getAlias('@api/runtime/files/');
        if (is_dir($runtime_files_dir)){
            $files = FileHelper::findFiles($runtime_files_dir);
            foreach ($files as $k => $v){
                unlink($v);
            }
        }
        /**
         * @var ImageIndex[] $files
         */
        $files = ImageIndex::find()->where(['<', 'updated_at', time()-86400*30])->all();
        foreach ($files as $k => $v){
            $file = $v->imageFilePath;
            if (file_exists($file)){
                if (unlink($file)){
                    echo $v->delete();
                }
            }
        }

        $t = time()-86400*30;
        $uploads_dir = \Yii::getAlias('@uploads_root/');
        $files = FileHelper::findFiles($uploads_dir, ['except'=>['.gitignore']]);
        foreach ($files as $k => $v){
            $file =  substr($v, strlen(dirname($v)) + 1);
            if (substr($file, 0, 10) < $t){
                $b = unlink($v);
                var_dump($b);
            }
        }
    }

    /**
     * php yii cron/delete-un-use-attsort-files
     */
    public function actionDeleteUnUseAttsortFiles()
    {
        $attsort_dir = \Yii::getAlias('@data/attsort/');
        $files = scandir($attsort_dir);
        $x = array_diff($files, ['.', '..', 'carloan.apk', 'app-carloan-release.apk', 'app-carloan-other.apk', 'remove.sh']);
        $x = array_values($x);
        $datas = Order::find()->select('o_number')->where(['in', 'o_status', ['初审提交', '审核中']])->asArray()->all();
        $y = [];
        foreach ($datas as $k => $v){
            $y[] = $v['o_number'];
        }
        $z = array_diff($x, $y);
        $z = array_values($z);
        $sh = \Yii::getAlias('@data/attsort/remove.sh');
        file_put_contents($sh, '');
        foreach ($z as $k => $v){
            if ($v){
                $dir = '/home/wwwroot/credit_ysjr/Uploads/AppFtp/attsort/'.$v;
                file_put_contents($sh, PHP_EOL.'rm '.$dir.' -rf'.PHP_EOL, FILE_APPEND);
            }
        }
    }
}